package com.cysyz.mylib.pdf.support;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;

/**
 * 以一个pdf中包含多页的形式来生成结果。
 * @author cy
 *
 */
public class PdfGeneraterWithTemplateAllInOnePdf implements WithTemplatePdfgenerter{

	@Override
	public void generatePdf(OutputFileNameGenerater outputFileNameGenerater,
			ByteArrayOutputStream[] afterReplacedPdfBytes,
			List<List<FieldConfig>> fieldConfigs) throws FileNotFoundException {
		Document document = new Document();
		PdfCopy copy = null;
		try {
			copy = new PdfCopy(document, new BufferedOutputStream(new FileOutputStream(outputFileNameGenerater.generate(fieldConfigs.get(0)))));
			document.open();
			for (ByteArrayOutputStream afterRplacedPdfByte : afterReplacedPdfBytes) {
				PdfReader afterReplacedPdfReader = new PdfReader(afterRplacedPdfByte.toByteArray());
				int numberOfPages = afterReplacedPdfReader.getNumberOfPages();
				for (int i = 1 ; i <= numberOfPages ; i ++) {
					PdfImportedPage importedPage = copy.getImportedPage(afterReplacedPdfReader, i);
					copy.addPage(importedPage);
				}
			}
		} catch (FileNotFoundException ex) {
			throw ex;
		} catch (DocumentException | IOException ex) {
			throw new RuntimeException(ex);
		} finally {
			if (copy != null) {
				copy.close();
			}
			if (document != null) {
				document.close();
			}
		}
		
	}

}
